import {markRaw, reactive, ref, shallowRef, toRaw, unref} from 'vue';
import {isEmpty, pageOptions, resolveOrderConfig, resolvePagination} from '@/utils/CommonUtils';

export default function ({refForm, doSearch, defaultSortConfig, searchParams, rowClick, selectionChange}) {
  const loading = shallowRef(false);
  const selectedRows = ref([]);
  const dataSource = reactive([]);
  const sortConfig = reactive(defaultSortConfig);
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 400,
  });

  function setSearchResult(result) {
    loading.value = false;
    if (isEmpty(result)) return;
    pagination.current = result.current;
    pagination.size = result.size;
    pagination.total = result.total;
    dataSource.length = 0;
    dataSource.push(...result.records);
  }

  function onRowClick(row) {
    rowClick(row);
  }

  function pageChange() {
    refForm.value.validate((valid, errors) => {
      if (valid) {
        loading.value = true;
        let searchData = {
          ...unref(searchParams),
          ...resolvePagination(toRaw(pagination)),
          ...resolveOrderConfig(toRaw(sortConfig))
        };
        doSearch(searchData);
      }
    });
  }

  function search(justReload = false) {
    refForm.value.validate((valid, errors) => {
      if (valid) {
        if (justReload === false) {
          pagination.current = 1;
          loading.value = true;
        }
        let searchData = {
          ...unref(searchParams),
          ...resolvePagination(toRaw(pagination)),
          ...resolveOrderConfig(toRaw(sortConfig))
        };
        doSearch(searchData);
      }
    });
  }

  function reload() {

  }

  function sortChange(config) {
    sortConfig.prop = config.prop;
    sortConfig.order = config.order;
    search();
  }

  function resetQueryParams() {
    try {
      refForm.value.resetFields()
    } catch (e) {
    }
  }

  function _selectionChange(rows) {
    selectedRows.value = rows;
    if (!isEmpty(selectionChange)) {
      selectionChange(rows);
    }
  }

  return {
    loading,
    setSearchResult,
    rowClick: onRowClick,
    search,
    pageOptions,
    pagination,
    dataSource,
    selectionChange: _selectionChange,
    sortChange,
    pageChange,
    resetQueryParams,
    sortConfig,
    selectedRows
  };
};
